package com.cobo.fitness.web.post.services.impl;
import com.cobo.fitness.web.fitness.vo.PostVo;
import com.cobo.fitness.web.post.entity.Category;
import com.cobo.fitness.web.post.entity.PostMeta;
import com.cobo.fitness.web.post.entity.Tag;
import com.cobo.fitness.web.post.services.CategoryService;
import com.cobo.fitness.web.post.services.PostMetaService;
import com.cobo.fitness.web.post.services.PostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cobo.fitness.web.post.entity.Post;
import com.cobo.fitness.web.post.mapper.PostMapper;
import com.cobo.fitness.web.post.services.TagService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PostServiceImpl  extends ServiceImpl<PostMapper, Post> implements PostService {

    @Autowired
    private TagService tagService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private PostMetaService postMetaService;

    @Override
    public void saveVo(PostVo postVo) {
        postVo.setAuthor("cobo");
        postVo.setCreateDate(new Date());
        postVo.setModifyDate(new Date());
        postVo.setModifyAuthor("cobo");
        postVo.setShortContent(StringUtils.substring(postVo.getContent(),0,200));
        String[] tags = postVo.getTags();
        String[] categorys = postVo.getCategorys();
        save(postVo);

        if (tags != null) {
            List<Tag> tagList = tagService.saveOrUpdateTag(tags);
            List<PostMeta> metas = tagList.stream().map(it -> {
                PostMeta postMeta = new PostMeta();
                postMeta.setTableName("tag");
                postMeta.setTableIdentify(it.getId());
                postMeta.setPostId(postVo.getId());
                return postMeta;
            }).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(metas)) {
                postMetaService.saveBatch(metas);
            }
        }

        if (tags != null) {
            List<Category> categoryList = categoryService.saveOrUpdateCategory(categorys);
            List<PostMeta> metas = categoryList.stream().map(it -> {
                PostMeta postMeta = new PostMeta();
                postMeta.setTableName("category");
                postMeta.setTableIdentify(it.getId());
                postMeta.setPostId(postVo.getId());
                return postMeta;
            }).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(metas)) {
                postMetaService.saveBatch(metas);
            }
        }

    }
}